import 'package:flutter/material.dart' hide ThemeMode;
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/app_theme.dart';
import '../models/user_settings.dart' as usersettingsmodel;

/// 设置页面
/// 提供用户偏好设置和应用配置选项
class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;

  UserSettings? _userSettings;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _loadSettings();
  }

  /// 初始化动画
  void _initAnimations() {
    _fadeController = AnimationController(
      duration: AppTheme.animationDurationMedium,
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
  }

  /// 加载设置
  Future<void> _loadSettings() async {
    try {
      final hiveService = Provider.of<HiveService>(context, listen: false);
      final settings = hiveService.getUserSettings();

      setState(() {
        _userSettings = settings;
        _isLoading = false;
      });

      _fadeController.forward();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('加载设置失败: $e');
    }
  }

  /// 保存设置
  Future<void> _saveSettings(UserSettings settings) async {
    try {
      final hiveService = Provider.of<HiveService>(context, listen: false);
      await hiveService.saveUserSettings(settings);

      setState(() {
        _userSettings = settings;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('设置已保存'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      _showErrorSnackBar('保存设置失败: $e');
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
      ),
    );
  }

  @override
  void dispose() {
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏
              _buildHeader(),

              // 设置内容
              Expanded(
                child: _isLoading
                    ? _buildLoadingState()
                    : _userSettings != null
                        ? _buildSettingsContent()
                        : _buildErrorState(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Row(
        children: [
          // IconButton(
          //   onPressed: () => Navigator.of(context).pop(),
          //   icon: const Icon(
          //     Icons.arrow_back,
          //     color: AppTheme.textPrimaryDark,
          //     size: AppTheme.iconSizeLarge,
          //   ),
          // ),
          const Expanded(
            child: Text(
              '设置',
              style: TextStyle(
                fontSize: AppTheme.fontSizeXL,
                fontWeight: FontWeight.bold,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          ),
          IconButton(
            onPressed: _showAboutDialog,
            icon: const Icon(
              Icons.info_outline,
              color: AppTheme.textSecondaryDark,
              size: AppTheme.iconSizeLarge,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
          ),
          SizedBox(height: AppTheme.spacingMedium),
          Text(
            '正在加载设置...',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textSecondaryDark,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建错误状态
  Widget _buildErrorState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: AppTheme.iconSizeXL,
            color: AppTheme.errorColor,
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          const Text(
            '加载设置失败',
            style: TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              color: AppTheme.textSecondaryDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _isLoading = true;
              });
              _loadSettings();
            },
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 构建设置内容
  Widget _buildSettingsContent() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: ListView(
        padding: const EdgeInsets.all(AppTheme.spacingMedium),
        children: [
          // 播放设置
          _buildSectionHeader('播放设置'),
          _buildPlaybackSettings(),

          const SizedBox(height: AppTheme.spacingLarge),

          // 音频设置
          _buildSectionHeader('音频设置'),
          _buildAudioSettings(),

          const SizedBox(height: AppTheme.spacingLarge),

          // 界面设置
          _buildSectionHeader('界面设置'),
          _buildUISettings(),

          const SizedBox(height: AppTheme.spacingLarge),

          // 其他设置
          _buildSectionHeader('其他设置'),
          _buildOtherSettings(),

          const SizedBox(height: AppTheme.spacingLarge),

          // 数据管理
          _buildSectionHeader('数据管理'),
          _buildDataManagement(),

          const SizedBox(height: AppTheme.spacingXL),
        ],
      ),
    );
  }

  /// 构建节标题
  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(
        left: AppTheme.spacingSmall,
        bottom: AppTheme.spacingMedium,
      ),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: AppTheme.fontSizeLarge,
          fontWeight: FontWeight.w600,
          color: AppTheme.primaryColor,
        ),
      ),
    );
  }

  /// 构建播放设置
  Widget _buildPlaybackSettings() {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
        border: Border.all(
          color: AppTheme.primaryColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: const Column(
        children: [
          // 播放模式功能暂未实现
          // _buildDropdownSetting(
          //   icon: Icons.repeat,
          //   title: '默认播放模式',
          //   value: '顺序播放',
          //   items: ['顺序播放', '随机播放', '单曲循环'],
          //   onChanged: (value) {},
          // ),

          // 自动播放功能暂未实现
          // _buildSwitchSetting(
          //   icon: Icons.skip_next,
          //   title: '自动播放下一首',
          //   subtitle: '当前音乐播放完毕后自动播放下一首',
          //   value: true,
          //   onChanged: (value) {},
          // ),

          // 记住播放位置功能暂未实现
          // _buildSwitchSetting(
          //   icon: Icons.bookmark,
          //   title: '记住播放位置',
          //   subtitle: '重新播放时从上次停止的位置开始',
          //   value: false,
          //   onChanged: (value) {},
          // ),
        ],
      ),
    );
  }

  /// 构建音频设置
  Widget _buildAudioSettings() {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
        border: Border.all(
          color: AppTheme.primaryColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          // 音质设置
          _buildDropdownSetting(
            icon: Icons.high_quality,
            title: '音质设置',
            value: _getAudioQualityDisplayName(_userSettings!.audioQuality),
            items: ['标准音质', '高音质', '无损音质'],
            onChanged: (value) {
              final quality = _parseAudioQuality(value);
              _saveSettings(_userSettings!.copyWith(audioQuality: quality));
            },
          ),

          const Divider(color: AppTheme.dividerDark, height: 1),

          // 音量设置
          _buildSliderSetting(
            icon: Icons.volume_up,
            title: '音量',
            value: _userSettings!.volume,
            min: 0.0,
            max: 1.0,
            divisions: 20,
            onChanged: (value) {
              _saveSettings(_userSettings!.copyWith(volume: value));
            },
            formatter: (value) => '${(value * 100).round()}%',
          ),

          const Divider(color: AppTheme.dividerDark, height: 1),

          // 淡入淡出
          _buildSwitchSetting(
            icon: Icons.graphic_eq,
            title: '淡入淡出效果',
            subtitle: '播放开始和结束时的音量渐变效果',
            value: _userSettings!.crossfadeEnabled,
            onChanged: (value) {
              _saveSettings(_userSettings!.copyWith(crossfadeEnabled: value));
            },
          ),
        ],
      ),
    );
  }

  /// 构建界面设置
  Widget _buildUISettings() {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
        border: Border.all(
          color: AppTheme.primaryColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          // 主题模式
          _buildDropdownSetting(
            icon: Icons.palette,
            title: '主题模式',
            value: _getThemeModeDisplayName(_userSettings!.themeMode),
            items: ['跟随系统', '浅色主题', '深色主题'],
            onChanged: (value) {
              final mode = _parseThemeMode(value);
              _saveSettings(_userSettings!.copyWith(themeMode: mode));
            },
          ),

          const Divider(color: AppTheme.dividerDark, height: 1),

          // 显示歌词
          _buildSwitchSetting(
            icon: Icons.lyrics,
            title: '显示歌词',
            subtitle: '在播放页面显示歌词（如果可用）',
            value: _userSettings!.lyricsEnabled,
            onChanged: (value) {
              _saveSettings(_userSettings!.copyWith(lyricsEnabled: value));
            },
          ),
        ],
      ),
    );
  }

  /// 构建其他设置
  Widget _buildOtherSettings() {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
        border: Border.all(
          color: AppTheme.primaryColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          // 睡眠定时器
          _buildDropdownSetting(
            icon: Icons.bedtime,
            title: '睡眠定时器',
            value: _getSleepTimerDisplayText(),
            items: _getSleepTimerOptions(),
            onChanged: (value) {
              final minutes = _parseSleepTimerValue(value);
              _saveSettings(
                  _userSettings!.copyWith(sleepTimerDuration: minutes));
            },
          ),

          const Divider(color: AppTheme.dividerDark, height: 1),

          // 自动扫描音乐功能暂未实现
          // _buildSwitchSetting(
          //   icon: Icons.scanner,
          //   title: '自动扫描音乐',
          //   subtitle: '启动时自动扫描新的音乐文件',
          //   value: false,
          //   onChanged: (value) {},
          // ),

          // 启用通知
          // 通知功能暂未实现
          // _buildSwitchSetting(
          //   icon: Icons.notifications,
          //   title: '启用通知',
          //   subtitle: '显示播放控制通知',
          //   value: false,
          //   onChanged: (value) {},
          // ),
        ],
      ),
    );
  }

  /// 构建数据管理
  Widget _buildDataManagement() {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
        border: Border.all(
          color: AppTheme.primaryColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          // 扫描音乐库
          _buildActionSetting(
            icon: Icons.refresh,
            title: '扫描音乐库',
            subtitle: '重新扫描本地音乐文件',
            onTap: _scanMusicLibrary,
          ),

          const Divider(color: AppTheme.dividerDark, height: 1),

          // 清空播放历史
          _buildActionSetting(
            icon: Icons.history,
            title: '清空播放历史',
            subtitle: '删除所有播放历史记录',
            onTap: _showClearHistoryDialog,
            isDestructive: true,
          ),

          const Divider(color: AppTheme.dividerDark, height: 1),

          // 重置设置
          _buildActionSetting(
            icon: Icons.restore,
            title: '重置设置',
            subtitle: '恢复所有设置到默认值',
            onTap: _showResetSettingsDialog,
            isDestructive: true,
          ),
        ],
      ),
    );
  }

  /// 构建开关设置项
  Widget _buildSwitchSetting({
    required IconData icon,
    required String title,
    String? subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: AppTheme.primaryColor,
        size: AppTheme.iconSizeMedium,
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: AppTheme.fontSizeMedium,
          color: AppTheme.textPrimaryDark,
        ),
      ),
      subtitle: subtitle != null
          ? Text(
              subtitle,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
              ),
            )
          : null,
      trailing: Switch(
        value: value,
        onChanged: onChanged,
        activeColor: AppTheme.primaryColor,
      ),
    );
  }

  /// 构建下拉选择设置项
  Widget _buildDropdownSetting({
    required IconData icon,
    required String title,
    required String value,
    required List<String> items,
    required ValueChanged<String> onChanged,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: AppTheme.primaryColor,
        size: AppTheme.iconSizeMedium,
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: AppTheme.fontSizeMedium,
          color: AppTheme.textPrimaryDark,
        ),
      ),
      trailing: DropdownButton<String>(
        value: value,
        items: items.map((item) {
          return DropdownMenuItem<String>(
            value: item,
            child: Text(
              item,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          );
        }).toList(),
        onChanged: (newValue) {
          if (newValue != null) {
            onChanged(newValue);
          }
        },
        dropdownColor: AppTheme.surfaceDark,
        underline: Container(),
      ),
    );
  }

  /// 构建滑块设置项
  Widget _buildSliderSetting({
    required IconData icon,
    required String title,
    required double value,
    required double min,
    required double max,
    int? divisions,
    required ValueChanged<double> onChanged,
    required String Function(double) formatter,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: AppTheme.primaryColor,
        size: AppTheme.iconSizeMedium,
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: AppTheme.fontSizeMedium,
          color: AppTheme.textPrimaryDark,
        ),
      ),
      subtitle: Column(
        children: [
          const SizedBox(height: AppTheme.spacingSmall),
          Row(
            children: [
              Expanded(
                child: Slider(
                  value: value,
                  min: min,
                  max: max,
                  divisions: divisions,
                  onChanged: onChanged,
                  activeColor: AppTheme.primaryColor,
                  inactiveColor: AppTheme.primaryColor.withOpacity(0.3),
                ),
              ),
              const SizedBox(width: AppTheme.spacingSmall),
              Text(
                formatter(value),
                style: const TextStyle(
                  fontSize: AppTheme.fontSizeSmall,
                  color: AppTheme.textSecondaryDark,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建操作设置项
  Widget _buildActionSetting({
    required IconData icon,
    required String title,
    String? subtitle,
    required VoidCallback onTap,
    bool isDestructive = false,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: isDestructive ? AppTheme.errorColor : AppTheme.primaryColor,
        size: AppTheme.iconSizeMedium,
      ),
      title: Text(
        title,
        style: TextStyle(
          fontSize: AppTheme.fontSizeMedium,
          color: isDestructive ? AppTheme.errorColor : AppTheme.textPrimaryDark,
        ),
      ),
      subtitle: subtitle != null
          ? Text(
              subtitle,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
              ),
            )
          : null,
      trailing: const Icon(
        Icons.chevron_right,
        color: AppTheme.textSecondaryDark,
      ),
      onTap: onTap,
    );
  }

  /// 获取睡眠定时器显示文本
  String _getSleepTimerDisplayText() {
    final minutes = _userSettings!.sleepTimerDuration;
    if (minutes == 0) {
      return '关闭';
    } else if (minutes < 60) {
      return '$minutes 分钟';
    } else {
      final hours = minutes ~/ 60;
      final remainingMinutes = minutes % 60;
      if (remainingMinutes == 0) {
        return '$hours 小时';
      } else {
        return '$hours 小时 $remainingMinutes 分钟';
      }
    }
  }

  /// 获取睡眠定时器选项
  List<String> _getSleepTimerOptions() {
    return [
      '关闭',
      '15 分钟',
      '30 分钟',
      '45 分钟',
      '1 小时',
      '1 小时 30 分钟',
      '2 小时',
    ];
  }

  /// 解析睡眠定时器值
  int _parseSleepTimerValue(String value) {
    switch (value) {
      case '关闭':
        return 0;
      case '15 分钟':
        return 15;
      case '30 分钟':
        return 30;
      case '45 分钟':
        return 45;
      case '1 小时':
        return 60;
      case '1 小时 30 分钟':
        return 90;
      case '2 小时':
        return 120;
      default:
        return 0;
    }
  }

  /// 获取主题模式显示名称
  String _getThemeModeDisplayName(usersettingsmodel.ThemeMode mode) {
    switch (mode) {
      case usersettingsmodel.ThemeMode.system:
        return '跟随系统';
      case usersettingsmodel.ThemeMode.light:
        return '浅色主题';
      case usersettingsmodel.ThemeMode.dark:
        return '深色主题';
    }
  }

  /// 解析主题模式
  usersettingsmodel.ThemeMode _parseThemeMode(String value) {
    switch (value) {
      case '跟随系统':
        return usersettingsmodel.ThemeMode.system;
      case '浅色主题':
        return usersettingsmodel.ThemeMode.light;
      case '深色主题':
        return usersettingsmodel.ThemeMode.dark;
      default:
        return usersettingsmodel.ThemeMode.system;
    }
  }

  /// 获取音质显示名称
  String _getAudioQualityDisplayName(AudioQuality quality) {
    switch (quality) {
      case AudioQuality.standard:
        return '标准音质';
      case AudioQuality.high:
        return '高音质';
      case AudioQuality.lossless:
        return '无损音质';
    }
  }

  /// 解析音质设置
  AudioQuality _parseAudioQuality(String value) {
    switch (value) {
      case '标准音质':
        return AudioQuality.standard;
      case '高音质':
        return AudioQuality.high;
      case '无损音质':
        return AudioQuality.lossless;
      default:
        return AudioQuality.high;
    }
  }

  /// 扫描音乐库
  void _scanMusicLibrary() async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);

      // 显示加载对话框
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const AlertDialog(
          backgroundColor: AppTheme.surfaceDark,
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(
                valueColor:
                    AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
              ),
              SizedBox(height: AppTheme.spacingMedium),
              Text(
                '正在扫描音乐库...',
                style: TextStyle(color: AppTheme.textPrimaryDark),
              ),
            ],
          ),
        ),
      );

      await musicLibraryService.scanLocalMusic();

      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('音乐库扫描完成'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
      }
      _showErrorSnackBar('扫描失败: $e');
    }
  }

  /// 显示清空历史对话框
  void _showClearHistoryDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '清空播放历史',
          style: TextStyle(color: AppTheme.textPrimaryDark),
        ),
        content: const Text(
          '确定要清空所有播放历史记录吗？\n此操作无法撤销。',
          style: TextStyle(color: AppTheme.textSecondaryDark),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              '取消',
              style: TextStyle(color: AppTheme.textSecondaryDark),
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _clearPlayHistory();
            },
            child: const Text(
              '确定',
              style: TextStyle(color: AppTheme.errorColor),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示重置设置对话框
  void _showResetSettingsDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '重置设置',
          style: TextStyle(color: AppTheme.textPrimaryDark),
        ),
        content: const Text(
          '确定要重置所有设置到默认值吗？\n此操作无法撤销。',
          style: TextStyle(color: AppTheme.textSecondaryDark),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              '取消',
              style: TextStyle(color: AppTheme.textSecondaryDark),
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _resetSettings();
            },
            child: const Text(
              '确定',
              style: TextStyle(color: AppTheme.errorColor),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示关于对话框
  void _showAboutDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '关于应用',
          style: TextStyle(color: AppTheme.textPrimaryDark),
        ),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Flutter 音乐播放器',
              style: TextStyle(
                fontSize: AppTheme.fontSizeLarge,
                fontWeight: FontWeight.bold,
                color: AppTheme.primaryColor,
              ),
            ),
            SizedBox(height: AppTheme.spacingSmall),
            Text(
              '版本: 1.0.0',
              style: TextStyle(
                fontSize: AppTheme.fontSizeMedium,
                color: AppTheme.textSecondaryDark,
              ),
            ),
            SizedBox(height: AppTheme.spacingMedium),
            Text(
              '一个现代化的音乐播放器应用，\n支持本地音乐播放、播放列表管理、\n收藏功能和播放历史记录。',
              style: TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              '确定',
              style: TextStyle(color: AppTheme.primaryColor),
            ),
          ),
        ],
      ),
    );
  }

  /// 清空播放历史
  void _clearPlayHistory() async {
    try {
      final databaseService =
          Provider.of<DatabaseService>(context, listen: false);
      await databaseService.clearTable('play_history');

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('播放历史已清空'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('清空失败: $e');
      }
    }
  }

  /// 重置设置
  void _resetSettings() async {
    try {
      final defaultSettings = UserSettings.defaultSettings();
      await _saveSettings(defaultSettings);

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('设置已重置'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('重置失败: $e');
      }
    }
  }
}
